package net.bwie.realtime.vehicle.job;

import com.alibaba.fastjson.JSON;
import net.bwie.realtime.jtp.common.utils.JdbcUtil;
import net.bwie.realtime.jtp.common.utils.KafkaUtil;
import net.bwie.realtime.vehicle.bean.CarBean;
import net.bwie.realtime.vehicle.bean.TripDetectionResult;
import net.bwie.realtime.vehicle.function.JourneyRealtimeFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

public class JourneyRealtimeAnalyseJob {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        // 从Kafka消费数据
        DataStream<String> kafkaStream = KafkaUtil.consumerKafka(env, "Realtime-vehicle-data");
        DataStream<TripDetectionResult> tripStream = kafkaStream
                .map(value -> JSON.parseObject(value, CarBean.class))
                .keyBy(CarBean::getVin)
                .process(new JourneyRealtimeFunction());
        // 输出结果
        SingleOutputStreamOperator<String> map = tripStream.map(
                new MapFunction<TripDetectionResult, String>() {
                    @Override
                    public String map(TripDetectionResult value) throws Exception {
                        return value.getVin() + ',' +
                                value.getTripId() + ',' +
                                value.getStartTime() + ',' +
                                value.getEndTime() + ',' +
                                value.getDistance();
                    }
                }
        );
//        map.print();
        String upsertSql = "INSERT INTO table vehicle_log.car_realtime (Vin, tripId, startTime, endTime,distance)\n" +
                "VALUES (?, ?, ?, ?,?)";
        JdbcUtil.sinkToClickhouseUpsert(map, upsertSql);
        env.execute("JourneyRealtimeAnalyseJob");
    }
}